package com.rudolfheszele.smsselector.controller;

import com.rudolfheszele.smsselector.model.SmsSelectorSmsMessage;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;

public class SmsSelectorSmsReceiver extends BroadcastReceiver
{
	@Override
	public void onReceive(Context context, Intent intent)
	{
		Bundle bundle = intent.getExtras();        
        SmsSelectorMainController mainController = (SmsSelectorMainController)ControllerFactoryFactory.getControllerFactory().getController();
        
        if (bundle != null)
        {
            Object[] pdus = (Object[]) bundle.get("pdus");
            
            for (int i = 0; i < pdus.length; i++)
            {
            	SmsMessage message = SmsMessage.createFromPdu((byte[])pdus[i]);
            	SmsSelectorSmsMessage smsMessage = SmsSelectorSmsMessage.createSmsMessage(message);
            	
            	if(mainController.isSmsReadingInProgress())
            		mainController.cacheIncomingMessage(smsMessage);
            	else
            		mainController.newSmsMessage(smsMessage);        
            }
        }
	}
}
